// pages/mood-select/mood-select.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    moodOptions: ['放松', '开心', '疲惫', '焦虑', '沮丧', '需要鼓励', '其它'],
    selectedMoods: [],
    showOtherInput: false,
    otherMood: '',
    showError: false,
    loading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    await this.loadMoodOptions();
    
    const app = getApp();
    // 如果有默认情绪，加载它
    if (app.globalData.selectedMoods && app.globalData.selectedMoods.length > 0) {
      this.setData({
        selectedMoods: [...app.globalData.selectedMoods]
      });
    }
  },

  // 从后端获取情绪选项
  async loadMoodOptions() {
    try {
      this.setData({ loading: true });
      const app = getApp();
      
      // 尝试从后端获取情绪选项
      const moodOptions = await app.apiService.getMoodOptions();
      
      if (moodOptions && moodOptions.length > 0) {
        this.setData({ 
          moodOptions: [...moodOptions, '其它'] // 添加"其它"选项
        });
      }
    } catch (error) {
      console.error('加载情绪选项失败:', error);
      // 保持默认选项不变
    } finally {
      this.setData({ loading: false });
    }
  },

  toggleMood: function(e) {
    const mood = e.currentTarget.dataset.mood;
    let selectedMoods = [...this.data.selectedMoods];
    
    // 处理"其它"选项
    if (mood === '其它') {
      this.setData({
        showOtherInput: !this.data.showOtherInput
      });
      // 如果已经选中"其它"，则取消
      const index = selectedMoods.indexOf('其它');
      if (index > -1) {
        selectedMoods.splice(index, 1);
        this.setData({
          otherMood: '',
          selectedMoods: selectedMoods
        });
      }
      return;
    }
    
    const index = selectedMoods.indexOf(mood);
    if (index > -1) {
      // 取消选中
      selectedMoods.splice(index, 1);
    } else {
      // 选中，但最多只能选2个
      if (selectedMoods.length >= 2) {
        // 如果已经有"其它"，且用户输入了内容，则移除第一个非"其它"的情绪
        const otherIndex = selectedMoods.indexOf('其它');
        if (otherIndex > -1 && this.data.otherMood) {
          selectedMoods.splice(otherIndex === 0 ? 1 : 0, 1);
        } else {
          selectedMoods.shift();
        }
      }
      selectedMoods.push(mood);
    }
    
    this.setData({
      selectedMoods: selectedMoods
    });
  },

  onOtherInput: function(e) {
    const value = e.detail.value;
    let selectedMoods = [...this.data.selectedMoods];
    
    if (value) {
      // 添加"其它"到选中列表
      if (!selectedMoods.includes('其它')) {
        if (selectedMoods.length >= 2) {
          selectedMoods.pop();
        }
        selectedMoods.push('其它');
      }
    } else {
      // 移除"其它"
      const index = selectedMoods.indexOf('其它');
      if (index > -1) {
        selectedMoods.splice(index, 1);
      }
    }
    
    this.setData({
      otherMood: value,
      selectedMoods: selectedMoods
    });
  },

  handleSkip: function() {
    const app = getApp();
    // 默认选中"放松"
    app.globalData.selectedMoods = ['放松'];
    app.saveUserInfo();
    
    wx.switchTab({
      url: '../index/index'
    });
  },

  async handleConfirm() {
    let selectedMoods = [...this.data.selectedMoods];
    
    // 检查是否选择了情绪
    if (selectedMoods.length === 0) {
      this.setData({
        showError: true
      });
      setTimeout(() => {
        this.setData({
          showError: false
        });
      }, 2000);
      return;
    }
    
    try {
      this.setData({ loading: true });
      
      // 处理"其它"情绪
      if (selectedMoods.includes('其它') && this.data.otherMood) {
        const index = selectedMoods.indexOf('其它');
        selectedMoods[index] = this.data.otherMood;
      }
      
      // 保存到全局数据
      const app = getApp();
      app.globalData.selectedMoods = selectedMoods;
      
      // 调用后端API保存用户情绪选择
      try {
        await app.apiService.saveUserMoods(selectedMoods);
      } catch (apiError) {
        console.error('保存情绪到后端失败:', apiError);
        // 即使API调用失败，也继续保存本地数据
      }
      
      // 保存本地数据作为降级方案
      app.saveUserInfo();
      
      wx.switchTab({
        url: '../index/index'
      });
    } catch (error) {
      console.error('确认情绪选择失败:', error);
      wx.showToast({
        title: '保存失败，请重试',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  }
})